package cn.byapps.hw.controller;

import cn.byapps.hw.entity.Student;
import cn.byapps.hw.service.StudentService;
import cn.byapps.hw.vo.StudentVO;
import cn.byapps.hw.vo.VueData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * StudentController
 */
@RestController
@RequestMapping("/api/student")
@Slf4j
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping
    public VueData<StudentVO> getList(Integer pos, Integer rows, Integer clazzId, String search) {
        int total = 0;
        List<StudentVO> list = null;
        if (clazzId == null) {
            if (search == null) {
                list = studentService.findVO(pos, rows);
                total = studentService.total();
            } else {
                list = studentService.findVO(pos, rows, search);
                total = studentService.totalBySearch(search);
            }
        } else {
            list = studentService.findVO(pos, rows, clazzId);
            total = studentService.total(clazzId);
        }
        VueData<StudentVO> vue = new VueData<StudentVO>(list, total);
        return vue;
    }

    @PostMapping
    public VueData<Student> add(@RequestBody Student student) {
        studentService.save(student);
        VueData<Student> vue = new VueData<>();
        return vue;
    }

    @PostMapping("/addbyclazz")
    public VueData<Student> add(@RequestBody Student student, Integer clazzId) {
        studentService.addByClazz(student, clazzId);
        VueData<Student> vue = new VueData<>();
        return vue;
    }

    @DeleteMapping
    public VueData<Student> delete(String id) {
        log.info("id = " + id);
        studentService.deleteById(id);
        VueData<Student> vue = new VueData<>();
        return vue;
    }

    @PutMapping
    public VueData<Student> update(@RequestBody Student student) {
        studentService.update(student);
        VueData<Student> vue = new VueData<>();
        return vue;
    }

}